/********************************************************************************
 * AddSubscriberAction.java
 *
 * Created by Jigar Mistry
 * Last modified Date: Sep 2, 2008 8:56:24 AM by Jigar Mistry
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/
package com.printeverywhere.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.MailGroupServiceDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.GroupUser;
import com.printeverywhere.dto.Groups;
import com.printeverywhere.dto.GroupuserId;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.SearchCriteria;

/**
 * The Class AddSubscriberAction.
 */
public class AddSubscriberAction extends AdminEngineManagement implements
		ServletRequestAware {

	/** Logger for this class. */
	private static final Logger logger = Logger
			.getLogger(AddSubscriberAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;
	/** The group list. */
	private List<Groups> groupList = MailGroupServiceDelegator.getGroupList();

	private List<User> addSubscriberUserList;

	/** The mail addresses. */
	private String mailAddresses;

	/** The groupId. */
	private String groupId;

	/** The groups. */
	private String groups[];

	/** The action. */
	private String action;

	private List<GroupUser> groupUser;

	private String deleteGroupId = null;

	/**
	 * @return the groupUser
	 */
	public List<GroupUser> getGroupUser() {
		return groupUser;
	}

	/**
	 * @param groupUser the groupUser to set
	 */
	public void setGroupUser(List<GroupUser> groupUser) {
		this.groupUser = groupUser;
	}

	/**
	 * Gets the action.
	 *
	 * @return the action
	 */
	public String getAction() {
		return action;
	}

	/**
	 * Sets the action.
	 *
	 * @param action
	 *            the new action
	 */
	public void setAction(String action) {
		this.action = action;
	}

	/**
	 * Gets the mail addresses.
	 *
	 * @return the mail addresses
	 */
	public String getMailAddresses() {
		return mailAddresses;
	}

	/**
	 * Sets the mail addresses.
	 *
	 * @param mailAddresses
	 *            the new mail addresses
	 */
	public void setMailAddresses(String mailAddresses) {
		this.mailAddresses = mailAddresses;
	}

	/**
	 * Show add new subscribers.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showAddNewSubscribers() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showAddNewSubscribers() - start"); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showAddNewSubscribers() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Adds the subscribers.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */

	public String addSubscribers() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("addSubscribers() - start"); //$NON-NLS-1$
		}

		if (groupId == null) {
			addActionMessage("Please Select Group for Subscription");
			return INPUT;
		} else {
			if (request.getParameter("submit") != null) {

				if (request.getParameter("checkedId") != null) {
					String[] checkedId = request
							.getParameterValues("checkedId");
					for (String chkid : checkedId) {
						if (deleteGroupId == null) {
							deleteGroupId = chkid;
						} else {
							deleteGroupId = deleteGroupId + " , " + chkid;
						}
					}
				}

				CommonFunctionDelegator
						.executeQuery("DELETE FROM GroupUser groupuser WHERE ((groupid = "
								+ groupId
								+ ") and userId IN ("
								+ deleteGroupId
								+ "))");

				if (request.getParameter("subscribedUser") != null) {
					String[] en = request.getParameterValues("subscribedUser");
					for (String string : en) {
						GroupuserId groupuserId = new GroupuserId();
						User user = UserServiceDelegator.getUser(Integer
								.parseInt(string));
						Groups groups = MailGroupServiceDelegator
								.getGroupById(Integer.parseInt(groupId));
						groupuserId.setUser(user);
						groupuserId.setGroups(groups);
						GroupUser groupUser = new GroupUser();
						groupUser.setId(groupuserId);
						MailGroupServiceDelegator
								.insertSubscriberToGroup(groupUser);
					}
				}
			}

			groupUser = MailGroupServiceDelegator.getGroupUserList(Integer
					.parseInt(groupId));
			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setOrderBy("id");
			searchCriteria.setAsc(true);
			addSubscriberUserList = UserServiceDelegator
					.getList(searchCriteria);

			int totalGroupUser = groupUser.size();
			int totalUser = addSubscriberUserList.size();
			int jIndex = 0;

			for (int index = 0; index < totalGroupUser; index++) {
				while (jIndex < totalUser) {
					int userId1 = ((User) addSubscriberUserList.get(jIndex))
							.getId();
					int userId2 = ((GroupUser) groupUser.get(index)).getId()
							.getUser().getId();
					if (userId1 == userId2) {
						((User) addSubscriberUserList.get(jIndex))
								.setChecked(true);
						jIndex++;
						break;
					} else {
						jIndex++;
					}
				}
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("AddSubscribers() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	@Override
	public void validate() {
		addSubscriberUserList = UserServiceDelegator.getList();

		for (Groups groups : groupList) {
			groups.setName(new StringBuffer(groups.getName()).append(" (")
					.append(
							MailGroupServiceDelegator
									.countGroupSubscriberById(groups
											.getGroupId())).append(")")
					.toString());
		}
	}

	/**
	 * Gets the group list.
	 *
	 * @return the group list
	 */
	public List<Groups> getGroupList() {
		return groupList;
	}

	/**
	 * Sets the group list.
	 *
	 * @param groupList
	 *            the new group list
	 */
	public void setGroupList(List<Groups> groupList) {
		this.groupList = groupList;
	}

	/**
	 * Gets the groups.
	 *
	 * @return the groups
	 */
	public String[] getGroups() {
		return groups;
	}

	/**
	 * Sets the groups.
	 *
	 * @param groups
	 *            the new groups
	 */
	public void setGroups(String[] groups) {
		this.groups = groups;
	}

	/**
	 * @return the addSubscriberUserList
	 */
	public List<User> getAddSubscriberUserList() {
		return addSubscriberUserList;
	}

	/**
	 * @param addSubscriberUserList the addSubscriberUserList to set
	 */
	public void setAddSubscriberUserList(List<User> addSubscriberUserList) {
		this.addSubscriberUserList = addSubscriberUserList;
	}

	/**
	 * @return the groupId
	 */
	public String getGroupId() {
		return groupId;
	}

	/**
	 * @param groupId the groupId to set
	 */
	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
}
